<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>魅力榜</title>
    <style>
        body {
            font-family: "Microsoft YaHei", sans-serif;
            background-color: #f7f7f7;
            margin: 0;
            padding: 40px;
            display: flex;
            justify-content: center;
            align-items: start;
            min-height: 100vh;
        }

        .container {
            max-width: 600px;
            width: 100%;
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
            padding: 20px;
            box-sizing: border-box;
        }

        h1 {
            text-align: center;
            color: #e74c3c;
            margin-bottom: 20px;
            font-size: 2em;
        }

        .rank-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 15px;
            border-bottom: 1px solid #eee;
        }

        .rank-info {
            font-size: 16px;
            color: #333;
        }

        .rank-info span.like {
            color: #e67e22;
            margin-left: 10px;
        }

        .send-flower-btn {
            background-color: #e74c3c;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s ease;
            font-size: 14px;
        }

        .send-flower-btn:hover {
            background-color: #c0392b;
        }
    </style>
</head>
<body onload="initPage()">
<div class="container">
    <h1>🌸 魅力榜 🌸</h1>
    <div id="rankListContainer">加载中...</div>
</div>

<script>
    let updateInterval = null;

    async function initPage() {
        try {
            // 初始化请求
            await fetch('/like/initData1');

            // 获取榜单数据
            const res = await fetch('/userLike/orderList1');
            if (!res.ok) {
                throw new Error('网络响应错误：' + res.status);
            }
            const data = await res.json();

            console.log("接收到的完整响应数据:", data); // 日志输出

            if (data.success && Array.isArray(data.list)) {
                renderRankList(data.list);
            } else {
                document.getElementById('rankListContainer').innerText = '暂无排行榜数据';
            }
        } catch (error) {
            console.error('初始化失败:', error);
            document.getElementById('rankListContainer').innerText = '加载数据失败，请检查网络或后端接口';
        }
    }

    function renderRankList(data) {
        const container = document.getElementById('rankListContainer');
        container.innerHTML = ''; // 清空旧内容

        if (!Array.isArray(data) || data.length === 0) {
            container.innerText = '暂无排行榜数据';
            return;
        }

        data.forEach(item => {
            if (!item || !item.userLike) {
                console.warn('发现无效数据项:', item);
                return;
            }

            const div = document.createElement('div');
            div.className = 'rank-item';

            div.innerHTML = `
                <div class="rank-info">
                    用户名：<span>${escapeHtml(item.userLike.username)}</span>
                    魅力值：<span class="like">${item.like}</span>
                </div>
                <button class="send-flower-btn" onclick="sendFlower(${item.userLike.id})">送花</button>
            `;

            container.appendChild(div);
        });
    }

    async function sendFlower(userId) {
        try {
            // 发送送花请求
            const res = await fetch(`/userLike/add1?id=${userId}`);
            if (!res.ok) {
                throw new Error('网络响应错误：' + res.status);
            }
            const result = await res.json();

            console.log("送花响应数据:", result);

            if (result.success && Array.isArray(result.list)) {
                alert('送花成功！');
                renderRankList(result.list); // 更新榜单
                startAutoUpdate(); // 启动定时刷新
            } else {
                alert('送花失败：' + result.mgs);
            }
        } catch (error) {
            console.error('送花请求失败:', error);
            alert('网络错误，送花失败');
        }
    }

    function startAutoUpdate() {
        if (!updateInterval) {
            updateInterval = setInterval(async () => {
                try {
                    const res = await fetch('/upDataMySql');
                    if (!res.ok) {
                        throw new Error('网络响应错误：' + res.status);
                    }
                    const data = await res.json();
                    if (data.success && Array.isArray(data.list)) {
                        renderRankList(data.list); // 刷新榜单
                    }
                } catch (err) {
                    console.error('自动刷新失败:', err);
                }
            }, 60000); // 每分钟一次
        }
    }

    // 防止XSS攻击的辅助函数
    function escapeHtml(str) {
        return str.replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }
</script>
</body>
</html>